package com.huluobo.a2209mdmdemo.views

import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.google.gson.Gson
import com.huluobo.lib_base.RoutePath
import com.hyphenate.EMCallBack
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMCursorResult
import com.hyphenate.chat.EMGroup
import com.hyphenate.chat.EMGroupInfo
import com.hyphenate.chat.EMMessage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import okhttp3.Dispatcher
import java.util.Collections

/**
 *  Created by LC on 2025/3/12.
 */

@Composable
fun GroupPage(navHostController: NavHostController) {
//    var groupList = remember {
//        mutableListOf<EMGroupInfo>()
//    }

    val groupList = remember {
        SnapshotStateList<EMGroupInfo>()
    }

    val joinedGroupList = remember {
        SnapshotStateList<EMGroup>()
    }

    var isJoined by remember {
        mutableStateOf(false)
    }

    LaunchedEffect(key1 = isJoined, block = {
        launch {
            runBlocking(Dispatchers.IO) {
                if (isJoined) {
                    joinedGroupList.clear()
                    joinedGroupList.addAll(EMClient.getInstance().groupManager().getJoinedGroupsFromServer())
                } else {
                    groupList.clear()
                    groupList.addAll(
                        EMClient.getInstance().groupManager()
                            .getPublicGroupsFromServer(10, "").data
                    )
                }
            }
        }
    })

    Column(
        Modifier
            .fillMaxWidth()
            .padding(20.dp)
    ) {
        Row(
            Modifier
                .fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "", Modifier.clickable {
                navHostController.popBackStack()
            })
            Text(text = "讨论组", textAlign = TextAlign.Center)
            Icon(imageVector = Icons.Default.Add, contentDescription = "", Modifier.clickable {
                //跳转到创建群
                navHostController.navigate(RoutePath.CREATE_GROUP)
            })
        }
        Spacer(modifier = Modifier.height(10.dp))
        Button(modifier = Modifier.fillMaxWidth(), onClick = {
            isJoined = !isJoined
        }) {
            if (!isJoined) {
                Text(text = "查找已加入的群")
            } else {
                Text(text = "查找所有群")
            }
        }

        LazyColumn(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(10.dp), content = {
            if (isJoined) {
                items(joinedGroupList) {
                    JoinedGroupItem(emGroupInfo = it, navHostController = navHostController)
                }
            } else {
                items(groupList) {
                    GroupItem(emGroupInfo = it, navHostController)
                }
            }
        })
    }
}

@Composable
fun GroupItem(emGroupInfo: EMGroupInfo, navHostController: NavHostController) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween,
        modifier = Modifier
            .padding(10.dp)
            .fillMaxWidth()
    ) {
        Text(text = emGroupInfo.groupName)
        Button(onClick = {
            EMClient.getInstance().groupManager().asyncJoinGroup(emGroupInfo.groupId, object : EMCallBack {
                override fun onSuccess() {
                    //加入成功,跳转到聊天页面
                    val chatBean = ChatBean(emGroupInfo.groupId, EMMessage.ChatType.GroupChat)
                    val json = Gson().toJson(chatBean)
                    runBlocking(Dispatchers.Main) {
                        navHostController.navigate(RoutePath.CHAT + "/$json")
                    }
                }

                override fun onError(code: Int, error: String?) {
                    Log.i("TagA", "加入讨论组失败:$error,code:$code")
                }
            })

        }) {
            Text(text = "加入讨论组")
        }
    }
}

@Composable
fun JoinedGroupItem(emGroupInfo: EMGroup, navHostController: NavHostController) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween,
        modifier = Modifier
            .padding(10.dp)
            .fillMaxWidth()
    ) {
        Text(text = emGroupInfo.groupName)
        Button(onClick = {
            val chatBean = ChatBean(emGroupInfo.groupId, EMMessage.ChatType.GroupChat)
            val json = Gson().toJson(chatBean)
            navHostController.navigate(RoutePath.CHAT + "/$json")
        }) {
            Text(text = "进群聊天")
        }
    }
}